package com.JUC;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class JUC08_ReadWriteLock {
    public static void main(String[] args) {

        MyCache myCache = new MyCache();
        for (int i = 1; i <= 5; i++){
            final int temp = i;
            new Thread(()->{
                myCache.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }
        for (int i = 1; i <= 5; i++) {
            final int temp = i;
            new Thread(()->{
                myCache.get(temp+"");
            },String.valueOf(i)).start();
        }
    }

}

class MyCache{
    private  volatile Map<String,Object> map = new HashMap<>();

    // 使用读写锁
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void put(String key, Object value){
        // 这是写操作，加写锁
        // 从 readWriteLock 对象中获取写锁
//        readWriteLock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\t++++写入数据"+key);
            //暂停一会儿，模拟网络拥堵
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t++++写入成功");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
//            readWriteLock.writeLock().unlock();
        }
    }

    public void get(String key){
        // 加读锁
//        readWriteLock.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+"\t读取数据");
            //暂停一会儿，模拟网络拥堵
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Object res = map.get(key);
            System.out.println(Thread.currentThread().getName()+"\t读取成功"+res);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
//            readWriteLock.readLock().unlock();
        }
    }
}
